// types/vote.d.ts
type VoteStatus = 'ongoing' | 'ended'

interface VoteDetail {
  id: number
  title: string
  status: VoteStatus
  endTime: string
  options: {
    id: number
    name: string
    votes: number
    percentage: number
  }[]
  participants: {
    userId: string
    avatar: string
    voteTime: string
  }[]

  totalVotes: number
  userVoted?: string // 用户选择的选项ID
}
import { detail, vote, Vote, VoteOption } from "../../../api/votes"
import { STORAGE_KEY } from "../../../api/config";
import {doLogin} from "../../../utils/util"
// vote.ts
Page({
  data: {
    voteData: null,
    factionTheme: 'horde',
    id: "",
    totalCount: 0,
    hasVotedFlag: false,
    canVoteFlag: false,
    selectedOptionId: "",
    userId:wx.getStorageSync(STORAGE_KEY.USER_ID),
    isOverTimed:false,
    loading:false
  },
  /**
  * 生命周期函数--监听页面加载
  */
  async onLoad(option: any) {
    console.log("页面跳转参数",option)
    this.setData({
      id: option.id
    })
    if(!wx.getStorageSync(STORAGE_KEY.USER_ID)){
      await doLogin()
    }
    // if(option.redirectTo){
    //   await doWxLogin()
    // }
    this.loadVoteData()
  },

  async loadVoteData() {
    try {
      const res = await detail(this.data.id)
      this.setData({
        voteData: res.data
      })
      this.processData(res.data)
    } catch (error) {
      wx.showToast({ title: '获取战报失败', icon: 'none' })
    }
  },
  async doVote() {
    console.log("点击投票按钮")
    this.setData({
      loading:true
    })
    if (this.data.hasVotedFlag) {
      wx.showToast({ title: '无法多次投票', icon: 'none' })
      return
    }
    try {
      let res = await vote(this.data.id, this.data.selectedOptionId)
      this.loadVoteData()
      this.setData({
        loading:false
      })
    } catch (error) {
      wx.showToast({ title: '冲锋失败！请重试', icon: 'none' })
      this.setData({
        loading:false
      })
    }
  },
  processData(data: Vote) {
    let totalCount = 0
    if(new Date().getTime() > new Date(data.endTime).getTime()){
       this.setData({
         isOverTimed:true
       })
    }
    else{
      this.setData({
        isOverTimed:false
      })
    }
    data.optionsList?.forEach((item) => {
      if (item.voteCount) {
        let imageUrls=[]
        totalCount += item.voteCount
        //添加optionsList对应的图片URL
        data.recordsList?.forEach((record)=>{
            if(record.voteOptionId == item.id){
              imageUrls.push(record.vxAvatar)
            }
        })
        item.votedAvatars=imageUrls
      }
    })
    // 计算百分比并排序
    const total = totalCount || 1 // 避免除以0
    data.optionsList = data.optionsList.map(opt => ({
      ...opt,
      percentage: Number(((opt.voteCount / total) * 100).toFixed(1))
    })).sort((a, b) => b.voteCount - a.voteCount)


    data.recordsList?.forEach((item) => {
      if (item.userId == this.data.userId) {
        this.setData({
          hasVotedFlag: true,
          canVoteFlag:false,
          selectedOptionId:item.voteOptionId
        })
      }
    })
    
    this.setData({
      voteData: data,
      // factionTheme: data.participants.length > 0 ? 
      //   data.participants.avatar.includes('horde') ? 'horde' : 'alliance' 
      //   : 'horde'
      factionTheme: 'alliance',
      totalCount: totalCount
    })
    console.log(this.data.voteData)
    console.log(this.data.selectedOptionId);
  },

  radioChange(e: any) {
    console.log(e.detail.value)
    this.setData({
      canVoteFlag: true,
      selectedOptionId: e.detail.value
    })
  },
  async handleVote(e: any) {
    const optionId = e.currentTarget.dataset.optionid
    if (this.data.hasVotedFlag) {
      wx.showToast({ title: '无法多次投票', icon: 'none' })
      return
    }
    if (!this.data.voteData?.status === 'ongoing') return

    try {
      let res = await vote(this.data.id, optionId)
      this.loadVoteData()
    } catch (error) {
      wx.showToast({ title: '冲锋失败！请重试', icon: 'none' })
    }
  },
  onShareAppMessage() {
    return {
      title: this.data.voteData.title,  // 标题限制40字‌:ml-citation{ref="4" data="citationList"}
      path: `/pages/vote/index/index?redirectTo=true&id=${this.data.id}`, // 路径需以/开头‌:ml-citation{ref="4,5" data="citationList"}
      imageUrl: 'https://wow.shuzhipeixian.com:12812/download/wow_collect/vote/sys/shareIcon.jpg' 
      // 推荐2:1比例WebP格式‌:ml-citation{ref="1,4" data="citationList"}
    }
  },
  onshareButton(){
    console.log("点击分享按钮")
    wx.showShareMenu({
      // title: '分享标题',
      // path: '/path/to/page',
      // imageUrl: '',
    })  
  }
})
